/* eslint-disable no-unused-vars */
import moment from 'moment-timezone';

// 是否为number
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

// 是否成功
function isSuccess(num, key, success) {
  if (!isNumber(num) || success === false) return false;
  var numb = Number(num);
  if (key === 'Y') {
    return numb >= 0 && numb <= 9999;
  } else if (key === 'M') {
    return numb >= 0 && numb <= 12 && num.length < 3;
  } else if (key === 'D') {
    return numb >= 1 && numb <= 31 && num.length < 3;
  } else if (key === 'H') {
    return numb >= 0 && numb <= 23 && num.length < 3;
  } else if (key === 'm' || key === 's') {
    return numb >= 0 && numb <= 59 && num.length < 3;
  } else if (key === 'S') {
    return numb >= 0 && numb <= 999 && num.length < 5;
  }
  return false;
}

// 解析时间格式，YYYY-MM-DD类型的
function parse(dateString) {
  const dateStr = dateString.replace(/(^\s*)|(\s*$)/g, '');
  const objKey = ['Y', 'M', 'D', 'H', 'm', 's', 'S'];
  let success = true;
  const dateArr = dateStr.split('');
  let step = [];
  const date = [];
  let format = '';
  let key = objKey.shift();

  for (var i = 0; i < dateArr.length; i++) {
    const value = dateArr[i];
    if (
      [':', ' ', '-', '.', '/'].indexOf(value) > -1 ||
      i === dateArr.length - 1
    ) {
      if (i === dateArr.length - 1) {
        step.push(value);
        format += key;
      } else {
        format += value;
      }
      let section = step.join('');
      if (key === 'Y') {
        section = ('20' + section).slice(-4);
      }
      success = isSuccess(section, key, success);
      if (success === false) break;
      date.push(section);
      step = [];
      key = objKey.shift();
    } else {
      step.push(value);
      format += key;
    }
  }

  if (success) {
    return {
      format: format,
      date: date
    };
  } else {
    return {
      format: '',
      date: dateStr
    };
  }
}

class TZ {
  constructor(config = {}) {
    this.customTz = config.tz;
    if (!this.customTz) throw new Error('tz no exist !');
    moment.locale('zh_CN',{
      week: {
        dow : 1
      }
    })
    this.moment = moment;
    this.isTimeStamp =
      config.isTimeStamp ||
      function(num) {
        return num > 1000000;
      };
    return this;
  }

  /**
   * 本地时间转换成UTC
   * @param {*} date
   * @param {*} format
   */
  LocalToUTC(date, format = 'YYYY-MM-DD HH:mm:ss') {
    if (this.isTime(date)) {
      return moment(date)
        .clone()
        .tz('UTC')
        .format(format);
    }

    return date;
  }

  /**
   * 本地时间转换成用户时间
   * @param {*} date
   * @param {*} format
   */
  LocalToCustom(date, format = 'YYYY-MM-DD HH:mm:ss') {
    if (this.isTime(date)) {
      return moment(date)
        .clone()
        .tz(this.customTz)
        .format(format);
    }
    return date;
  }

  /**
   * UTC转换成本地时间
   * @param {*} date
   * @param {*} format
   */
  // UTCToLocal(date, format = 'YYYY-MM-DD HH:mm:ss') {
  //     if (this.isTime(date)) {
  //         return moment.tz(date, 'UTC').clone().format(format)
  //     }
  //     return date
  // }

  /**
   * 事件转换默认为utc时间
   * 转换为用户时间
   * @param {*} date
   * @param {*} format
   */
  UTCToCustom(date, format = 'YYYY-MM-DD HH:mm:ss') {
    return this.transform(date, 'UTC', this.customTz, format);
  }

  /**
   * utc时间转换成客户时间
   * @param {*} date
   * @param {*} format
   */
  CustomToUTC(date, format = 'YYYY-MM-DD HH:mm:ss') {
    return this.transform(date, this.customTz, 'UTC', format);
  }

  CustomToTimestamp(e){return this.transformStamp(e,this.customTz,"UTC")}

  timestampToCustom(date,format){
    return format
    ? moment.tz(parseInt(date),this.customTz).format(format)
    : date
  }



  // CloneToCustomByUTC(data) {}

  // CloseToUTCByCustom() {}

  transform(date, startTz, endTz, format = 'YYYY-MM-DD HH:mm:ss') {
    if (this.isTime(date)) {
      return moment
        .tz(date, startTz)
        .clone()
        .tz(endTz)
        .format(format);
    }
    return date;
  }

  transformStamp(e,a,n) {
    return this.isTime(e)||moment.isMoment(e)
          ? moment.tz(e,a).clone().tz(n).toDate().getTime()
          : e
  }

  isTime(obj) {
    const checkMap = {
      '[object String]': date => {
        return (
          String(date).match(/^\d{2,4}[-\s:\/\.]\d{1,2}[-\s:\/\.]\d{1,2}/) &&
          String(date).match(/^[-\s:\/\.0-9]+$/)
        );
      },
      '[object Number]': num => {
        return this.isTimeStamp(num);
      },
      '[object Object]': obj => {
        return obj instanceof moment;
      },
      '[object Date]': () => true
    };
    const type = Object.prototype.toString.call(obj);
    if (typeof checkMap[type] === 'function') {
      return checkMap[type](obj);
    }
    return obj;
  }
  // 时间处理小时
  timeCycle(x,unit="minutes"){
    var tempTime = moment.duration(x,unit).asSeconds();
    return this.secondsFormat(tempTime)
  }
  secondsFormat( s ) {
    var hour = Math.floor( (s / 3600));
    var minute = Math.floor((s - hour* 3600)/60);
    var seconds = s - hour * 3600 - minute * 60;
    return hour + '时' + minute +  '分' + seconds +  '秒';
  }
  millisecondFormat( s ) {
    var hour = Math.floor( (s / 3600000));
    var minute = Math.floor((s - hour * 3600000)/60000);
    var seconds = Math.floor((s - hour * 3600000 - minute * 60000)/1000);
    return hour + '时' + minute +  '分' + seconds +  '秒';
  }
}

export default TZ;
